package com.ym.ganio.gan;

import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

/**
 * Created by yumodev on 17/6/7.
 */

public abstract class RecyclerViewLoadMoreScrollListener extends RecyclerView.OnScrollListener {

    private RecyclerView.LayoutManager mLayoutManager = null;
    private int mLastVisiblePostion = 0;

    public RecyclerViewLoadMoreScrollListener(RecyclerView.LayoutManager layoutManager){
        mLayoutManager = layoutManager;
    }
    @Override
    public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
        super.onScrollStateChanged(recyclerView, newState);

        // 在newState为滑到底部时
        if (newState == RecyclerView.SCROLL_STATE_IDLE) {
            // 如果没有隐藏footView，那么最后一个条目的位置就比我们的getItemCount少1，自己可以算一下
            if (mLastVisiblePostion + 1 == mLayoutManager.getItemCount()) {
                loadMore();
            }

//            // 如果隐藏了提示条，我们又上拉加载时，那么最后一个条目就要比getItemCount要少2
//            if (adapter.isFadeTips() == true && lastVisibleItem + 2 == adapter.getItemCount()) {
//               loadMore();
//            }
        }
    }

    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        super.onScrolled(recyclerView, dx, dy);
            // 在滑动完成后，拿到最后一个可见的item的位置
        if (mLayoutManager instanceof LinearLayoutManager){
            mLastVisiblePostion = LinearLayoutManager.class.cast(mLayoutManager).findLastVisibleItemPosition();
        }

        if (mLayoutManager instanceof GridLayoutManager){
            mLastVisiblePostion = GridLayoutManager.class.cast(mLayoutManager).findLastVisibleItemPosition();
        }
    }

    protected abstract void loadMore();
}
